using System;
using System.Diagnostics;
using System.IO;

namespace MultiTCPProxy.Services
{
    /// <summary>
    /// 调试日志类，用于记录程序运行时的详细信息
    /// </summary>
    public static class DebugLogger
    {
        private static readonly string LogFilePath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
            "MultiTCPProxy",
            "debug.log");

        static DebugLogger()
        {
            try
            {
                string directory = Path.GetDirectoryName(LogFilePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
            }
            catch
            {
                // 忽略目录创建失败的错误
            }
        }

        /// <summary>
        /// 记录调试信息
        /// </summary>
        public static void Log(string message, LogLevel level = LogLevel.Info)
        {
            try
            {
                string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{level}] {message}";
                Debug.WriteLine(logMessage);

                File.AppendAllText(LogFilePath, logMessage + Environment.NewLine);
            }
            catch
            {
                // 忽略日志写入失败的错误
            }
        }

        /// <summary>
        /// 记录异常信息
        /// </summary>
        public static void LogException(Exception ex, string context = null)
        {
            try
            {
                string message = context != null ? $"{context}: {ex}" : ex.ToString();
                Log(message, LogLevel.Error);
            }
            catch
            {
                // 忽略日志写入失败的错误
            }
        }
    }

    /// <summary>
    /// 日志级别
    /// </summary>
    public enum LogLevel
    {
        Debug,
        Info,
        Warning,
        Error
    }
} 